<template>
    <a-modal
      :bodyStyle="bodyStyle"
      :title="title"
      :visible="visible"
      :confirmLoading="confirmLoading"
      :destroyOnClose="true"
      :maskClosable="false"
      @ok="handleOk"
      @cancel="handleCancel"
    >
      <a-form layout='vertical' :form="form">
        <a-form-item>
          <a-upload
              listType="picture-card"
              class="avatar-uploader"
              :showUploadList="false"
              :beforeUpload="beforeUpload"
              v-decorator="['photoImage',{}]"
            >
              <img v-if="imageUrl" :src="imageUrl" alt="avatar"/>
              <div v-else>
                  <a-icon :type="loading ? 'loading' : 'plus'" />
                  <div class="ant-upload-text">Upload</div>
              </div>
            </a-upload>
          <span>注意文件名规则：文件名+下划线+标签，如：Z00001_新中式 荷花.jpg</span>
        </a-form-item>
        <a-form-item>
          <a-input
            v-decorator="[
              'name',
              {
                rules: [{ required: true, message: '请输入名称!' }],
              }
            ]"
            placeholder="请输入名称"
          />
        </a-form-item>
        <a-form-item>
          <a-input
            v-decorator="[
              'tag',
              {
                rules: [{ required: false, message: '请输入标签!' }],
              }
            ]"
            placeholder="请输入标签"
          />
        </a-form-item>
        <a-form-item>
          <a-checkbox
            :checked="onlySearch"
            @change="onChangeOnlySearch"
            v-decorator="[
              'onlySearch',
              {
                rules: [{ required: false }],
              }
            ]"
          >只能以图搜索</a-checkbox>
        </a-form-item>
        <a-form-item>
          <a-tree-select
            :treeData="treeData"
            :value="classifyIds"
            @change="onChange"
            treeCheckable
            :dropdownStyle="{ maxHeight: '400px', overflow: 'auto' }"
            :showCheckedStrategy="SHOW_PARENT"
            searchPlaceholder="Please select"
          />
        </a-form-item>
        <a-form-item class="form-item-hidden">
          <a-input type="hidden" v-decorator="['id', {}]"/>
        </a-form-item>
      </a-form>
    </a-modal>
</template>
<script>
import api from '@/core/Api'
import serv from './ImageStoreService'
import Vue from 'vue'
import { TreeSelect, Form, Upload, Button, Checkbox, Input, Modal } from 'ant-design-vue'
const SHOW_PARENT = TreeSelect.SHOW_PARENT
Vue.component(Form.name, Form)
Vue.component(Form.Item.name, Form.Item)
Vue.component(Upload.name, Upload)
Vue.component(Button.name, Button)
Vue.component(Checkbox.name, Checkbox)
Vue.component(Input.name, Input)
Vue.component(TreeSelect.name, TreeSelect)
Vue.component(Modal.name, Modal)
export default {
  beforeCreate () {
    this.form = this.$form.createForm(this)
  },
  created () {
    this.productTypes = this.dictionary().PRODUCT_TYPE
  },
  data () {
    return {
      bodyStyle: { height: 400 },
      productTypes: [],
      loading: false,
      imageUrl: '',
      onlySearch: false,

      classifyIds: [],
      treeData: [],
      SHOW_PARENT
    }
  },
  props: {
    title: {
      type: String,
      required: true
    },
    visible: {
      type: Boolean,
      default: false
    },
    confirmLoading: {
      type: Boolean,
      default: false
    },
    data: {
      type: Object,
      default () {
        return {}
      }
    }
  },
  watch: {
    visible: function (nvalue) {
      // 初始加载树
      !nvalue || this.getTree()

      if (nvalue && Object.keys(this.data).length > 0) {
        console.log(this.data)
        setTimeout(() => {
          this.form.setFieldsValue(this.data)
        }, 10)
        this.onlySearch = this.data.onlySearch
        this.imageUrl = this.data.url
        if (this.data.id) this.getImageStorageAndClassifyList(this.data.id)
      } else {
        this.imageUrl = ''
        this.classifyIds = []
      }
    }
  },
  methods: {
    handleOk (e) {
      this.$emit('ok', this.classifyIds)
    },
    handleCancel (e) {
      this.$emit('cancel')
    },
    onChange (value) {
      console.log(value)
      this.classifyIds = value
    },
    onChangeOnlySearch (e) {
      this.onlySearch = e.target.checked
    },
    beforeUpload (file) {
      const isJPG = file.type === 'image/jpeg'
      if (!isJPG) {
        this.$message.error('You can only upload JPG file!')
      }
      const isLt2M = file.size / 1024 / 1024 < 3
      if (!isLt2M) {
        this.$message.error('图不能大于 2MB!')
      }
      const r = isJPG && isLt2M
      if (r) {
        api.getBase64(file, (imageUrl) => {
          this.imageUrl = imageUrl
          const name = api.getName(file.name)
          // let {groups: {one, two}} = /^(?<one>.+)[＿_]?(?<two>.*)$/u.exec(api.getName(file.name))
          let index = name.indexOf('_')
          if (index === -1) {
            index = name.indexOf('＿')
          }
          if (index > -1) {
            this.data.name = name.substring(0, index)
            this.data.tag = name.substring(index + 1)
          } else {
            this.data.name = name
          }

          this.form.setFieldsValue(this.data)
          this.loading = false
        })
      }
      return false
    },
    onChangeUrl (e) {
      console.log(11212)
    },
    async getTree () {
      this.treeData = await serv.getTree()
    },
    onSelect (selectedKeys, info) {
      console.log('selected', selectedKeys, info)
    },
    onCheck (checkedKeys, info) {
      console.log('onCheck', checkedKeys, info)
    },
    async getImageStorageAndClassifyList (id) {
      const ids = []
      for (let item of await serv.getImageStorageAndClassifyList(id)) {
        console.log(item)
        ids.push(item.imageStorageClassifyId)
      }
      this.classifyIds = ids
    }
  }
}
</script>

<style scoped>
img {
  max-width: 100%;
}
</style>
